<template>
  <cl-drawer ref="drawer" :props="{
    title: `维护`,
    size: '850px',
    appendToBody: true
  }" showConfirm confirmText="提交" @close="reset" @confirm="submit" :saving="saving">
    <el-form ref="form" label-position="top" :model="form" :rules="rules" :disabled="saving">
      <el-form-item label="维护信息">
        <el-card shadow="never">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="维护门店" prop="dept_id">
                <cl-shop-select v-model="form.dept_id" placeholder="请选择维护门店" filterable style="width: 100%"
                  :biz_id="form.biz_id" only-open @change="changeDept" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="维护品牌" prop="bra_id">
                <cl-select v-model="form.bra_id" placeholder="请选择品牌" style="width: 100%">
                  <el-option v-for="item in bizRefData.brand" :key="item.bra_id" :label="item.bra_name"
                    :value="item.bra_id" />
                </cl-select>
              </el-form-item>
            </el-col>

            <!-- v-if="form.develop.length > 0" -->
            <el-col :span="12">
              <el-form-item label="是否指定维护时间" prop="timeIsok" required>
                <el-radio-group v-model="form.timeIsok" @change="timeIsokChange">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- v-if="
								(form.develop.length > 0 && form.timeIsok == 1) ||
									form.develop.length == 0
							" -->
            <template v-if="form.timeIsok == 1">

              <el-col :span="12">
                <el-form-item label="维护时间" prop="appoint_time">
                  <!-- <cl-shop-datetime-picker
										:biz_id="form.biz_id"
										:dept_id="form.dept_id"
										:date.sync="form.appoint_date"
										:time.sync="form.appoint_btime"
										v-model="form.appoint_time"
									/> -->
                  <div style="display: flex;">
                    <el-input v-model="form.appoint_time" type="text" placeholder="请填写预约时间" disabled>
                    </el-input>
                    <el-button style="margin-left: 5px;" type="primary" size="mini" @click="onSelectTime">选择预约时间</el-button>
                  </div>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="维护时长" prop="cart_duration">
                  <cart-duration v-model="form.cart_duration" style="width: 100%" />
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-card>
      </el-form-item>
      <el-form-item label="维护项目">
        <el-card shadow="never">
          <el-table :data="form.maintain" border stripe class="mb-2">
            <el-table-column type="index" label="序号" align="center" width="80" />
            <el-table-column prop="si_name" label="服务项目" align="center" />
            <el-table-column label="数量" align="center">1</el-table-column>
            <el-table-column label="价格(￥)" align="center"> 0 </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="maintainkDel(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex flex-justify-center">
            <cl-choice-service v-model="form.maintain" :biz_id="form.biz_id" :disabled-list="form.develop"
              @confirm="onMaintainConfirm" btnText="添加维护项目" />
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="开发项目">
        <el-card shadow="never">
          <el-table :data="form.develop" border stripe class="mb-2">
            <el-table-column type="index" label="序号" align="center" width="80" />
            <el-table-column prop="si_name" label="服务项目" align="center" />
            <el-table-column label="数量" align="center">1</el-table-column>
            <el-table-column label="价格(￥)" prop="price" align="center">
              <template slot-scope="{ row, $index }">
                <el-form-item :prop="`develop.${$index}.price`" :rules="rules.develop_price" :show-message="false"
                  :inline-message="true">
                  <el-input v-model.number="row.price" @blur="row.price = Number($event.target.value)"
                    oninput="value=value.replace(/[^\d^\.]/g,'')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="{ $index }">
                <el-button type="text" @click="developDel($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex flex-justify-center">
            <cl-choice-service v-model="form.develop" :biz_id="form.biz_id" :disabled-list="form.maintain"
              btnText="添加开发项目" />
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" placeholder="请填写备注" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
  </cl-drawer>
</template>

<script>
import dayjs from "dayjs";
import CartDuration from "@/components/cart-duration.vue";
export default {
  name: "maintain-form",
  inject: ["$layout"],
  components: {
    CartDuration
  },
  data() {
    const appointTimeValidator = (rule, value, callback) => {
      const { appoint_date, appoint_btime } = this.form;
      if (!appoint_date || !appoint_btime) {
        return callback(new Error("请选择维护时间"));
      }
      return callback();
    };

    return {
      form: {
        cus_id: "",
        biz_id: "",
        dept_id: "",
        timeIsok: 1,
        appoint_time: "",
        appoint_date: "",
        appoint_btime: "",
        cart_duration: "",
        maintain: [],
        develop: [],
        remarks: "",
        bra_id: ""
      },
      rules: {
        dept_id: [{ required: true, message: "请选择门店" }],
        bra_id: [{ required: true, message: "请选择品牌" }],

        appoint_time: [{ required: true, validator: appointTimeValidator }],
        cart_duration: [{ required: true, message: "请选择维护时长" }],
        maintain: [{ required: false, message: "维护项目不能为空" }],
        develop_price: [{ required: true, message: "请填写开发项目价格" }]
      },
      saving: false,
      detail: {},
      cart_duration_disabled: false,
    };
  },
  computed: {
    bizRefData() {
      const { biz_id } = this.detail;
      return this.getBizRefData(biz_id);
    }
  },
  methods: {
    open(detail) {
      this.$refs.drawer.create();
      this.detail = { ...detail };
      this.initAppointTime();
      Object.keys(this.form).forEach(k => {
        detail[k] != undefined && (this.form[k] = detail[k]);
      });
      this.getShopList();
      this.getService();
    },
    initAppointTime() {
      let now = dayjs();
      let nowAfter1h = now.add(1, "h").minute(0);
      let diffM = nowAfter1h.diff(now, "m");
      now = now.add(diffM > 30 ? diffM - 30 : diffM, "m");
      this.form.appoint_date = now.format("YYYY-MM-DD");
      this.form.appoint_btime = now.format("HH:mm");
      this.form.appoint_time = [this.form.appoint_date, this.form.appoint_btime].join(" ");
    },
    selectTimeCall(data = null) {
      if (!data) return false;
      console.log('data',data);
      
      this.form.city_id = data.city_id;
      this.form.dept_id = data.dept_id;
      this.form.appoint_time = data.appoint_time;
      this.form.appoint_date = data.appoint_date;
      this.form.appoint_btime = data.appoint_btime;
      this.form.bed = data.bed;
      if (data.cart_duration > 0) {
        this.cart_duration_disabled = true;
        this.form.cart_duration = data.cart_duration;
      }
      else {
        this.cart_duration_disabled = false;
      }
    },
    // 选择预约时间
    onSelectTime() {
      // console.log(this.browser,this.form);
      // if(this.browser.isMobile){
      //       this.showTimePop = true
      //             this.mobile_appoint_time=new Date(dayjs().format("YYYY-MM-DD"))

      // }else{
      const { biz_id, dept_id, cart_duration, city_id, appoint_info = {} } = this.form;
      // const { cart_duration, city_id } = appoint_info;
      const { cus_type } = this;
      const params = {
        biz_id: biz_id,
        dept_id: dept_id,
        cart_duration: cart_duration,
        city_id: city_id,
        cus_type
      };
      this.$layout.openAppointBoard(
        params,
        "选择预约时间",
        "selectTime",
        this.selectTimeCall
      );
      // }

    },
    submit() {
      this.$refs.form.validate(async (valid, errors) => {
        this.showFormErr(errors);
        if (!valid) return;
        const { maintain, develop, ...args } = this.form;
        if (!maintain.length && !develop.length) {
          this.$message.warning("维护项目或者开发项目必须有一项不能为空");
          return;
        }
        let maintainItems = maintain.map(v => {
          return {
            prod_id: v.si_id,
            prod_name: v.si_name,
            maintain_type: 1,
            price: 0
          };
        });
        let developItems = develop.map(v => {
          return {
            prod_id: v.si_id,
            prod_name: v.si_name,
            maintain_type: 2,
            price: v.price
          };
        });
        let form = {
          ...args,
          items: JSON.stringify([...maintainItems, ...developItems])
        };
        this.saving = true;
        await this.$service.cart.maintain(form).done(() => {
          this.saving = false;
        });
        this.$message.success("操作成功");
        this.$emit("confirm");
        this.close();
      });
    },
    maintainkDel(idx) {
      this.form.maintain.splice(idx, 1);
      if (!this.form.maintain.length) {
        this.$refs.form.validateField("maintain");
      }
    },
    developDel(idx) {
      this.form.develop.splice(idx, 1);
    },
    onMaintainConfirm() {
      this.$refs.form.validateField("maintain");
    },
    async getShopList() {
      const { biz_id } = this.detail;
      this.getBizRefShop(biz_id);
    },
    async getService() {
      const { cus_id } = this.form;
      this.form.maintain = [];
      if (!cus_id) return;
      const data = await this.$service.cart.getService({ cus_id });
      this.form.maintain = data;
    },
    reset() {
      this.$resetFields(this.form);
      this.form.timeIsok = 1;
      this.$refs.form?.resetFields?.();
    },
    close() {
      this.reset();
      this.$refs.drawer.close();
    },
    // 是否指定预约时间
    timeIsokChange(v) {
      if (v) {
        this.initAppointTime();
        return;
      }
      this.form.appoint_date = "";
      this.form.appoint_btime = "";
    },

    changeDept(val) {
      // this.form.dept_id = v[1];
      // this.form.cus_id = "";
      if (!val) return;
      this.form.appoint_btime = "";
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-col {
    min-height: 77px;
  }

  .el-table {
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }
}
</style>
